var mimeType = {
	types : {
		"3gp" : "video/3gpp",
		"apk" : "application/vnd.android.package-archive",
		"asf" : "video/x-ms-asf",
		"avi" : "video/x-msvideo",
		"bin" : "application/octet-stream",
		"bmp" : "image/bmp",
		"c" : "text/plain",
		"class" : "application/octet-stream",
		"conf" : "text/plain",
		"cpp" : "text/plain",
		"css" : "text/css",
		"doc" : "application/msword",
		"docx" : "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
		"xls" : "application/vnd.ms-excel",
		"xlsx" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
		"exe" : "application/octet-stream",
		"gif" : "image/gif",
		"gtar" : "application/x-gtar",
		"gz" : "application/x-gzip",
		"h" : "text/plain",
		"htm" : "text/html",
		"html" : "text/html",
		"ico" : "image/x-icon",
		"jar" : "application/java-archive",
		"java" : "text/plain",
		"jpeg" : "image/jpeg",
		"jpg" : "image/jpeg",
		"js" : "application/x-javascript",
		"log" : "text/plain",
		"m3u" : "audio/x-mpegurl",
		"m4a" : "audio/mp4a-latm",
		"m4b" : "audio/mp4a-latm",
		"m4p" : "audio/mp4a-latm",
		"m4u" : "video/vnd.mpegurl",
		"m4v" : "video/x-m4v",
		"mov" : "video/quicktime",
		"mp2" : "audio/x-mpeg",
		"mp3" : "audio/x-mpeg",
		"mp4" : "video/mp4",
		"mpc" : "application/vnd.mpohun.certificate",
		"mpe" : "video/mpeg",
		"mpeg" : "video/mpeg",
		"mpg" : "video/mpeg",
		"mpg4" : "video/mp4",
		"mpga" : "audio/mpeg",
		"msg" : "application/vnd.ms-outlook",
		"ogg" : "audio/ogg",
		"pdf" : "application/pdf",
		"png" : "image/png",
		"pps" : "application/vnd.ms-powerpoint",
		"ppt" : "application/vnd.ms-powerpoint",
		"pptx" : "application/vnd.openxmlformats-officedocument.presentationml.presentation",
		"prop" : "text/plain",
		"rc" : "text/plain",
		"rmvb" : "audio/x-pn-realaudio",
		"rtf" : "application/rtf",
		"sh" : "text/plain",
		"tar" : "application/x-tar",
		"tgz" : "application/x-compressed",
		"txt" : "text/plain",
		"wav" : "audio/x-wav",
		"wma" : "audio/x-ms-wma",
		"wmv" : "audio/x-ms-wmv",
		"wps" : "application/vnd.ms-works",
		"xml" : "text/plain",
		"z" : "application/x-compress",
		"zip" : "application/x-zip-compressed",
		"" : "*/*"
	},
	getTypes : function(exts) {
		var arr = exts.split(","), mt = "";
		for (var index = 0; index < arr.length; index ++) {
			var ext = arr[index];
			if (!mt) mt += this.types[ext];
			else mt += "," + this.types[ext];
		}
		return mt;
	}
};
var uploader = {
	fileSize : 100 * 1024 * 1024,
	num : 0,
	uploaders : {},
	uploadcontroller : {},
	onlyread : false,
	keysuccessstatus : {},
	uploadkey : [],
	haskey : [],
	allkey : [],
	callback : null,
	createFileObj : function(params){
		var fileObj = new Object();
		fileObj["size"] = params.size ? params.size : this.fileSize;
		fileObj["num"] = params.num ? params.num : this.num;
		fileObj["url"] = params.url;
		fileObj["files"] = [];
		fileObj["delids"] = [];
		fileObj["successdata"] = [];
		fileObj["loadfilecount"] = 0;
		fileObj["delcount"] = 0;
		this.uploaders[params.key] = fileObj;
	},
	createHeadHtml : function(params, onlyread){
		var $uploaderdiv = $("body").find("div[uploaderKey="+params.key+"]");
		var $table = $uploaderdiv.find("table[class='uploadtable']");
		var $tbody = $("<tbody></tbody>");
		if(!onlyread){
			var $limit = mimeType.getTypes(params.limit);
			var $file = $("<input style=\"display:none;\" id=\""+params.key+"\" multiple=\"multiple\" accept=\""+$limit+"\" type=\"file\" />");
			$uploaderdiv.prepend($file);
			$table.append("" +
					"<thead>" +
					"<tr>" +
					"<th width=\"36%\">文件名&nbsp;&nbsp;|&nbsp;&nbsp;<span class=\"fileselect\" style=\"color: #1E9FFF;cursor: pointer;\">选择文件</span></th>" +
					"<th width=\"18%\">大小</th>" +
					"<th width=\"18%\">状态</th>" +
					"<th width=\"28%\">操作</th>" +
					"</tr>" +
			"</thead>");
			$table.append($tbody);
			
			$table.find("span[class='fileselect']").bind("click",function(){
				$file.click();
			});
			
			$file.bind("change",function(){
				uploader.change($file, $tbody, params.key);
			});
		}else{
			$table.append("" +
					"<thead>" +
					"<tr>" +
					"<th width=\"70%\">文件名</th>" +
					"<th width=\"30%\">操作</th>" +
					"</tr>" +
			"</thead>");
			$table.append($tbody);
		}
		this.uploaders[params.key]["table"] = $table;
		this.uploaders[params.key]["tbody"] = $tbody;
	},
	createBodyHtml : function(params, $tbody, $key){
		var _size;
		if(params.size > 1024 * 1024){
			_size = (params.size / (1024 * 1024)).toFixed(2) + " MB";
		}else{
			_size = (params.size / 1024).toFixed(2) + " KB";
		}
		var _td = $("" +
			"<tr>" +
				"<td></td>" +
				"<td></td>" +
				"<td></td>" +
				"<td></td>" +
			"</tr>"
		);
		var $processTitle;
		var $processFather;
		var $process;
		
		var _$uploadcontroller;
		
		_td.find("td").append(function(n){
			if(n == 0){
				return $("<span title=\""+params.name+"\">"+params.name+"</span>");
			}else if(n == 1){
				return _size;
			}else if(n == 2){
				$processTitle = $("<span>等待上传</span>");
				$processFather = $("<div style=\"width:100%; height:15px; border:1px solid; display:none;\"></div>");
				$process = $("<div style=\"background-color:#69d888; height:100%; width:0px;\"></div>");
				$processFather.append($process);
				var $div = $("<div style=\"width:100%;height:100%;\"></div>");
				$div.append($processTitle);
				$div.append($processFather);
				return $div;
			}else if(n == 3){
				var _delBtn = $("<span style=\"background-color:#FF5722; color:#fff; padding:5px;cursor: pointer\">删除<span>");
				_delBtn.bind("click",function(){
					var delObj;
					$.each(uploader.uploaders[$key].successdata,function(i,v){
						if(v.localName == params.name){
							delObj = v;
							return false;
						}
					});
					if(delObj){
						uploader.uploaders[$key].successdata.remove(delObj);
					}
					if(_$uploadcontroller){
						uploader.uploadcontroller[$key].remove(_$uploadcontroller);
					}
					uploader.uploaders[$key].files.remove(params);
					$(this).parent().parent().remove();
				});
				return _delBtn;
			}
		});
		$tbody.append(_td);
		
		//创建上传Xhr
		_$uploadcontroller = this.createFileUpload($key, $process, $processFather, $processTitle, $(_td.find("td")[3]), params);
	},
	init : function(params,callback,onlyread){
		var $this = this;
		this.onlyread = onlyread ? onlyread : false;
		this.callback = callback;
		$.each(params,function(i,v){
			$this.allkey.push(v.key);
			$this.createFileObj(v);
			$this.createHeadHtml(v, $this.onlyread);
		});
	},
	change : function($file, $tbody, $key){
		var _files = $file.get(0).files;
		if(_files.length == 0) return;
		
		if(!this.isOverSize(_files, $key)){
			$file.get(0).value = "";
			return;
		}
		if(!this.isOverNum(_files, $key)){
			$file.get(0).value = "";
			return;
		}
		
		$.each(_files,function(i,v){
			if(uploader.pushOjb(v, $key)){
				uploader.createBodyHtml(v, $tbody, $key);
			}
		});
		
		$file.get(0).value = "";
	},
	pushOjb : function(file, $key){
		var iscreate = true;
		if(uploader.uploaders[$key].files.length == 0){
			uploader.uploaders[$key].files.push(file);
		}else{
			$.each(uploader.uploaders[$key].files,function(i,v){
				if(file.name == v.name){
					search.info({content: "列表中已存在该文件!"});
					iscreate = false;
					return false;
				}
			});
			if(iscreate){
				uploader.uploaders[$key].files.push(file);
			}
		}
		return iscreate;
	},
	isOverSize : function(_files, $key){
		var _size;
		var fileSize = this.uploaders[$key].size;
		if(fileSize > 1024 * 1024){
			_size = (fileSize / (1024 * 1024)).toFixed(2) + " MB";
		}else{
			_size = (fileSize / 1024).toFixed(2) + " KB";
		}
		var next = true;
		$.each(_files,function(i,v){
			if(v.size > fileSize){
				search.info({content: "文件大小超过"+_size});
				next = false;
				return false;
			}
		})
		return next;
	},
	isOverNum : function(_files, $key){
		var _uploader = this.uploaders[$key];
		var _num = _uploader.num;
		var next = true;
		var _nownum = (_uploader.loadfilecount + _uploader.successdata.length + _uploader.files.length) - _uploader.delcount;
		if(_num > 0){
			if(_nownum + _files.length > _num){
				search.info({content: "上传文件个数超过"+_num+"个"});
				next = false;
				return false;
			}
		}
		return next;
	},
	loadFiles : function($key, _files){
		if(_files && _files.length > 0){
			$.each(_files,function(i,v){
				uploader.uploaders[$key].loadfilecount++;
				uploader.loadFilesHtml(v, $key, uploader.onlyread);
			});
		}
	},
	loadFilesHtml : function(params, $key, onlyread){
		var $tbody = this.uploaders[$key].tbody;
		if(!onlyread){
			var _td = $("" +
				"<tr>" +
					"<td></td>" +
					"<td></td>" +
					"<td></td>" +
					"<td></td>" +
				"</tr>"
			);
			_td.find("td").append(function(n){
				if(n == 0){
					return $("<span title=\""+params.attachname+"\">"+params.attachname+"</span>");
				}else if(n == 1){
					return "";
				}else if(n == 2){
					return "已上传";
				}else if(n == 3){
					var Btns = $("<div></div>");
					var _delBtn = $("<span style=\"background-color:#FF5722; color:#fff; padding:5px;cursor: pointer\">删除<span>");
					_delBtn.bind("click",function(){
						var $_td = $(this).parent().parent().parent();
						search.confirm({
							content : "确定要删除该附件吗?",
							funl : function(){
								uploader.uploaders[$key].delcount++;
								uploader.uploaders[$key].delids.push(params.entityid);
								$_td.remove();
							}
						});
					});
					var _lookBtn = $("<span style=\"background-color:#1E9FFF; color:#fff; padding:5px;cursor: pointer; margin-left:5px;\">预览<span>");
					_lookBtn.bind("click",function(){
						uploader.viewImage(params.attachname, params.attachpath);
					});
					var _downBtn = $("<span style=\"background-color:#009688; color:#fff; padding:5px;cursor: pointer; margin-left:5px;\">下载<span>");
					_downBtn.bind("click",function(){
						uploader.downloadImage(params.attachname, params.attachpath);
					});
					Btns.append(_delBtn);
					Btns.append(_lookBtn);
					Btns.append(_downBtn);
					return Btns;
				}
			});
			$tbody.append(_td);
		}else{
			var _td = $("" +
					"<tr>" +
						"<td></td>" +
						"<td></td>" +
					"</tr>"
				);
			_td.find("td").append(function(n){
				if(n == 0){
					return $("<span title=\""+params.attachname+"\">"+params.attachname+"</span>");
				}else if(n == 1){
					var Btns = $("<div></div>");
					var _lookBtn = $("<span style=\"background-color:#1E9FFF; color:#fff; padding:5px;cursor: pointer; margin-left:5px;\">预览<span>");
					_lookBtn.bind("click",function(){
						uploader.viewImage(params.attachname, params.attachpath);
					});
					var _downBtn = $("<span style=\"background-color:#009688; color:#fff; padding:5px;cursor: pointer; margin-left:5px;\">下载<span>");
					_downBtn.bind("click",function(){
						uploader.downloadImage(params.attachname, params.attachpath);
					});
					Btns.append(_lookBtn);
					Btns.append(_downBtn);
					return Btns;
				}
			});
			$tbody.append(_td);
		}
	},
	downloadImage : function(name, path){
		var form = "<form id='attachDownloadForm' action='" + __ctx + "/attach/df.xhtml' method='post' target='_blank' style='display: none;'>" + 
		   "<input name='name' type='hidden' value='" + name + "'/>" + 
		   "<input name='path' type='hidden' value='" + path + "'/>" + 
		   "</form>";
		$(form).appendTo("body").submit().remove();
	},
	viewImage : function (name, path){
		var win = $(top.window);
		var url = __ctx + "/attach/vi.xhtml?name=" + name + "&path=" + path;
		var data = {
			url : encodeURI(url),
			width : win.width(),
			height : win.height(),
			modal : false
		};
		top.search.popDialog(data);
	},
	createFileUpload : function($key, $process, $processFather, $processTitle, $btnTd, _file){
		var obj = new Object();
		obj["key"] = $key;
		obj["process"] = $process;
		obj["processFather"] = $processFather;
		obj["processTitle"] = $processTitle;
		obj["btnTd"] = $btnTd;
		obj["file"] = _file;
		obj["overupload"] = false;
		if(this.uploadcontroller[$key]){
			this.uploadcontroller[$key].push(obj);
		}else{
			this.uploadcontroller[$key] = [obj];
		}
		return obj;
	},
	sendAjax : function(uploadObj){
		var $key = uploadObj.key, $process = uploadObj.process, $processFather = uploadObj.processFather, $processTitle = uploadObj.processTitle, $btnTd = uploadObj.processTitle, _file = uploadObj.file;
		var form = new FormData();
		form.append('file', _file);
		$.ajax({
			url : this.uploaders[$key].url,
			data : form,
			type : 'POST',
			contentType:false,
			processData:false,
			xhr : function(){
				var myXhr = $.ajaxSettings.xhr();
			    if(myXhr.upload) {
			    	 myXhr.upload.addEventListener('progress',function(event){
			    		 var loaded = event.loaded;   //已经上传大小情况 
			    		 var tot = event.total;      //附件总大小 
			    		 var per = Math.floor(100*loaded/tot);  //已经上传的百分比
			    		 $process.css("width",per +"%");
			    	 }, true);     
			    	 return myXhr;
			    }
			},
			success : function(result){
				if(result.status){
					$processTitle.html("上传成功");
					$processFather.hide();
					$processTitle.show();
					uploadObj["overupload"] = true;
					uploader.uploaders[$key].successdata.push(result.result[0]);
					uploader.fileUploadCallBack($key);
				}else{
					$processTitle.html("上传失败");
					$processTitle.css("color","red");
					$processFather.hide();
					$processTitle.show();
				}
			},
			error : function(){
				$processTitle.html("上传失败");
				$processTitle.css("color","red");
				$processFather.hide();
				$processTitle.show();
				//重新上传 已屏蔽
//				var _restBtn = $("<span style=\"background-color:#009688; color:#fff; padding:5px;cursor: pointer; margin-left:5px;\">重新上传<span>");
//				_restBtn.bind("click",function(){
//					uploader.restSend($key, $process, $processFather, $processTitle, $btnTd, _restBtn, _file);
//				});
//				$btnTd.append(_restBtn);
			}
		});
	},
	fileUploadCallBack : function($key){
		if(this.uploaders[$key].successdata.length == this.uploaders[$key].files.length){
			this.keysuccessstatus[$key] = true;
		}
		var isback = true;
		$.each(this.uploadkey,function(i,v){
			if(!uploader.keysuccessstatus[v]){
				isback = false;
				return false;
			}
		});
		if(isback){
			this.toBack();
		}
	},
	toBack : function(){
		var params = new Object();
		$.each(this.uploadkey,function(i,v){
			var obj = new Object();
			obj["uploads"] = uploader.uploaders[v].successdata;
			obj["deletes"] = uploader.uploaders[v].delids;
			params[v] = obj;
		});
		this.callback(params);
	},
	upload : function(keyArrays){
		if(keyArrays){
			this.uploadkey = keyArrays;
		}else{
			this.uploadkey = this.allkey;
		}
		var pass = true;
		$.each(this.uploadkey,function(i,$key){
			uploader.keysuccessstatus[$key] = false;
			if(uploader.uploadcontroller[$key] && uploader.uploadcontroller[$key].length > 0){
				$.each(uploader.uploadcontroller[$key],function(j,xhr){
					if(!xhr.overupload){
						pass = false;
						uploader.sendAjax(xhr);
					}
				});
			}
		});
		if(pass){
			this.toBack();
		}
	},
	hasFile : function(keyArrays){
		if(keyArrays){
			this.haskey = keyArrays;
		}else{
			this.haskey = this.allkey;
		}
		var next = true;
		$.each(this.haskey,function(i,$key){
			if(uploader.uploaders[$key].files.length == 0){
				if(uploader.uploaders[$key].loadfilecount == uploader.uploaders[$key].delcount){
					next = false;
					return false;
				}
			}
		});
		return next;
	}
};
